package main.java.indi.zyj.hot100;

import java.util.*;

public class _63_topKFrequent {
    public int[] topKFrequent(int[] nums, int k) {

        int len = nums.length;
        Map<Integer, Integer> occurnce = new HashMap<>();

        for (int i = 0; i < len; i++) {
            occurnce.put(nums[i], occurnce.getOrDefault(nums[i], 0) + 1);
        }

        PriorityQueue<int[]> queue = new PriorityQueue<>((int[] m, int[] n) -> m[1] - n[1] );

        for (Map.Entry<Integer, Integer> entry : occurnce.entrySet()){
            int key = entry.getKey(), val = entry.getValue();
            if (queue.size() == k){
                if (queue.peek()[1] < val){
                    queue.poll();
                    queue.offer(new int[]{key, val});
                } else {
                    queue.offer(new int[]{key, val});
                }
            }
        }
        int[] ret = new int[k];
        for (int i = 0; i < k; ++i) {
            ret[i] = queue.poll()[0];
        }
        return ret;
    }
}
